<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>LayIM测试</title>
    <link rel="stylesheet" href="./static/layui/css/layui.css" media="all">
</head>
<body>
<div id="loginform" style="display: none">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="username"  autocomplete="off" placeholder="请输入昵称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="1" title="男" checked="">
                <input type="radio" name="sex" value="0" title="女">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="*">提交</button>
            </div>
        </div>
    </form>
</div>

<script src="./static/layui/layui.js"></script>
<script>
    layui.use(['layim','form'], function(layim){
        var $ = layui.jquery;
        var form = layui.form();
        var userInfo = {
            "username": ""
            ,"id": 0 //我的ID
            ,"status": "online" //在线状态 online：在线、hide：隐身
            ,"avatar": "" //我的头像};
        };
        var socket;

        function init(){
            userInfo = {};

            initUser(function(userInfo){
                initWs(function(){
                    let request = {
                        mine:{
                            username:userInfo.username
                        },
                        to:{
                            'type':'init'
                        },
                    };
                    socket.send(JSON.stringify(request))
                })
            })
        }

        function initUser(handlerInitSuccess){
            layer.open({
                type: 1,
                title:'登录',
                skin: 'layui-layer-rim', //加上边框
                area: ['420px', '240px'], //宽高
                content: $("#loginform").html()
            });

            form.render(); //更新全部

            form.on('submit(*)', function(data){
                let fields = data.field;
                userInfo.username = fields.username;
                userInfo.avatar = fields.sex == 1  ? "./static/imgs/icon2.jpg" : "./static/imgs/icon.jpg";
                layer.closeAll();
                handlerInitSuccess(userInfo);
                return false;
            });
        }

        function initWs(handlerInitSuccess){
            socket = new WebSocket('ws://42.192.87.76:7000/ws');

            socket.onopen = function(){
                let request = {
                    mine:{
                        username:userInfo.username
                    },
                    to:{
                        'type':'init'
                    },
                };
                socket.send(JSON.stringify(request))
            };

            socket.onmessage = function(res){
                switch (res.type) {
                    case 'message':
                        let message = JSON.parse(res.data);
                        if(message.type == "init"){
                            userInfo.id = message.user_id;
                            initIm();
                        }else{
                            layim.getMessage(message); //res.data即你发送消息传递的数据（阅读：监听发送的消息）
                        }
                }
            };

            socket.onerror = function(){
                console.log("连接异常")
            };
            socket.onclose = function(){
                console.log("连接关闭")
            };
        }

        function initIm(){
            layim.config({
                brief: false,
                title:"聊天室",
                isfriend:true,
                init:{
                    mine: userInfo,
                    group: [{
                        "groupname": "欢乐大家庭" //群组名
                        ,"id": 1 //群组ID
                        ,"avatar": "./static/imgs/family.jpg" //群组头像
                    }],
                },
                members: {
                    url: '/api/im/getMembers/',
                    data: {}
                },
                copyright:true
            });

            // // 发送消息
            layim.on('sendMessage', function(res){
                socket.send(JSON.stringify(res))
            });
        }

        init();
    });


</script>
</body>
</html>